<template>
  <div class="layoutBox">
    <div class="siderBox">
      <h3>通讯录</h3>
      <a-menu style="width: 256px" mode="vertical" @click="handleClick">
        <a-menu-item key="1">指控车1</a-menu-item>
        <a-menu-item key="2">指控车2</a-menu-item>
        <a-menu-item key="3">指控车3</a-menu-item>
        <a-menu-item key="4">指控车4</a-menu-item>
      </a-menu>
    </div>
    <div class="rightBox">
      <div class="headerBox">正在与指控车X通讯发送速率 :XXXkbps 接收速率: XXkbps</div>
      <div class="chactBox">
        <div class="chactDiv">
          <ul class="ulBox">
            <li class="Misconduct">
              设备A :
              <span>xxxxxxx</span>
            </li>
            <li class="Local">
              <span>我不要</span>
            </li>
          </ul>
        </div>
        <div class="inputDiv">
          <a-textarea placeholder="输入内容。。。" :rows="10" />
          <div class="handleDiv">
            <a-button type="primary">查找记录</a-button>
            <a-button type="primary">选择文件</a-button>
            <a-button type="primary">发送</a-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getAction, httpAction } from '@/api/manage.js'
// import { msgList, conversationList } from '@/api/customerService'
const columns = [
  {
    scopedSlots: { customRender: 'serial' }
  }]
export default {
  name: 'CurrentChat',
  components: {
  },
  watch: {
    messageList: function (val) {
      if (val.length > 0) {
        this.refresh()
      }
    }
  },
  data() {
    this.columns = columns
    return {

      url: {
        conversationList: '/123',
        msgList: "/3445",
      },

      // 大于10条显示分页
      messageList: [],
      timestamp: undefined,
      moreRecordsFlag: false,
      conversationForm: [],
      conversationFlagList: [],
      paginationFlag: false,
      midCard: undefined,
      clearTimeSet: undefined, // 定时器
      handleVisible: false,
      viewPictureSrc: undefined,
      fromUserid: '',
      userInfo: {
        name: '',
        mobile: '',
        from: '',
        userId: '',
        clientType: ''
      },
      path: '',
      socket: '',
      // 查询参数
      queryParam: {
        saleSn: undefined,
        consignee: undefined,
        mobile: undefined,
        saleStatus: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      form: {
        response: ''
      },
      params: {
        clientType: 0,
        limit: 10,
        order: 'desc',
        page: 1,
        userId: undefined,
        sort: 'add_time',
        timestamp: undefined
      }
    }
  },
  mounted() {
    // this.getMsgList()
    // this.getConversationList()
    // setInterval(() => {
    //   this.reConnect()
    // }, 60000)
  },
  watch: {
    messageList: function (val) {
      if (val.length > 0) {
        this.refresh()
      }
    }
  },
  methods: {
    handleClick(e) {
      console.log('click ', e);
    },
    getMsgList() {
      getAction(this.url.msgList, this.params).then(res => {
        const { errno } = res
        if (errno === 0) {
          const tempMessageList = res.data && res.data.list ? res.data.list : []
          this.moreRecordsFlag = true
          if (tempMessageList.length === 0) {
            this.moreRecordsFlag = false
          }
          tempMessageList.reverse()
          this.messageList = tempMessageList.concat(this.messageList)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getMoreMsg() {
      this.params.timestamp = new Date(this.messageList[0].addTime).getTime()
      this.getMsgList()
    },
    async sendMsg() {
      if (this.form.response.replace(/ /g, '').length === 0) {
        this.$message.error('请勿回复空白')
        return false
      }
      if (!this.isOnlineCurrUser(this.socket)) {
        this.socket = ''
        this.init()
        this.$message.info('已离线，正在重连')
        // this.socket = ''
        // setInterval(this.init(), 1000)
        // this.init()
        this.$message.success('连接成功')
        return
        // this.sendMsg()
        // this.socket.send(JSON.stringify(parmas))
      } else {
        const parmas = {
          clientType: this.params.clientType,
          content: this.form.response,
          fromUserid: sessionStorage.getItem('adminId'),
          msgType: 0,
          toUserid: this.userInfo.userId
        }

        this.socket.send(JSON.stringify(parmas))
        const yy = new Date().getFullYear()
        const mm = new Date().getMonth() + 1
        const dd = new Date().getDate()
        const hh = new Date().getHours()
        const mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
        const time = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf
        parmas.addTime = time
        this.messageList.push(parmas)
      }
      // await sendToUserId(parmas)
      // this.params.timestamp = undefined
      // msgList(this.params).then(res => {
      //   const { errno } = res
      //   if (errno === 0) {
      //     const tempMessageList = res.data && res.data.list ? res.data.list : []
      //     if (tempMessageList.length === 0) {
      //       this.moreRecordsFlag = false
      //     }
      //     this.messageList.push(tempMessageList[0])
      //   }
      // }).catch(err => {
      //   console.log(err)
      // })
      this.form.response = undefined
    },
    getConversationList() {
      const params = {
        limit: 10,
        order: 'desc',
        page: 1,
        sort: 'add_time'
      }
      httpAction(this.url.conversationList, params, 'post').then(res => {
        const { errno } = res
        if (errno === 0) {
          this.conversationForm = res.data && res.data.list ? res.data.list : []
          this.conversationForm.forEach(e => {
            this.conversationFlagList.push(e.inservice === 0 && e.viewed === 0)
          })
          this.paginationFlag = (res.data.total > 9)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    reConnect() {
      if (!this.isOnlineCurrUser(this.socket) && this.userInfo.userId !== '') {
        this.socket = ''
        this.init()
      }
    },
    init: function () {
      if (typeof (WebSocket) === 'undefined') {
        this.$message.error('您的浏览器不支持socket')
      } else {
        // 实例化socket
        this.path = 'wss://dev.tianmiwo.com/api/webSocket/' + this.userInfo.userId + '-' + sessionStorage.getItem('adminId')
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
        const parmas = {
          clientType: this.params.clientType,
          fromUserid: sessionStorage.getItem('adminId'),
          msgType: -3,
          toUserid: this.userInfo.userId
        }
        this.setTimer(parmas)
      }
    },
    open: function () {
      console.log('socket连接成功')
    },
    error: function () {
      console.log('连接错误')
    },
    getMessage: function (msg) {
      console.log('---------------------------')
      // console.log(msg)
      console.log(msg.data)
      const yy = new Date().getFullYear()
      const mm = new Date().getMonth() + 1
      const dd = new Date().getDate()
      const hh = new Date().getHours()
      const mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
      const time = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf
      const data = JSON.parse(msg.data)
      if (data.content === 'pong') {
        return
      }
      data.addTime = time
      this.messageList.push(data)
      console.log('---------------------------')
    },
    send: function () {
      // this.socket.send(params)
    },
    close: function () {
      console.log('socket已经关闭')
    },
    // 选择会话
    click(record, index) {
      return {
        on: {
          click: () => {
            this.selectChat(record, index)
          }
        }
      }
    },
    // 选择会话
    selectChat(record, index) {
      if (this.socket !== '') {
        this.socket.onclose = this.close
        this.socket.close()
        this.clearTimer()
      }
      this.$set(this.conversationFlagList, index, false)
      this.messageList = []
      this.params.userId = record.userid
      this.params.clientType = record.clientType
      this.getMsgList()
      this.userInfo.name = record.username
      this.userInfo.mobile = '(' + (record.mobile ? record.mobile : '--') + ')'
      this.userInfo.userId = record.userid
      this.userInfo.clientType = record.clientType
      switch (record.clientType) {
        case 0:
          this.userInfo.from = '来自会员端'
          break
        case 1:
          this.userInfo.from = '来自管理端'
          break
        case 2:
          this.userInfo.from = '来自收银台'
          break
        case 3:
          this.userInfo.from = '来自后台'
          break
      }
      // 初始化
      this.init()
      this.refresh()
    },
    // 滚动条置底
    refresh() {
      this.$nextTick(() => {
        // this.midCard = this.$refs.midCard
        // console.log(this.midCard.scrollHeight)
        document.getElementsByClassName('midCard')[0].scrollTop = document.getElementsByClassName('midCard')[0].scrollHeight
        // console.log(document.getElementsByClassName('midCard')[0].scrollTop)
        // console.log(document.getElementsByClassName('midCard')[0].scrollHeight)
      })
    },
    /**
   * 判断当前用户是否 还在线
   */
    isOnlineCurrUser(ws) {
      if (ws) {
        if (ws.readyState === WebSocket.OPEN) {
          return true
        } else {
          return false
        }
      } else {
        return false
      }
    },
    // 设置定时器
    setTimer(parmas) {
      this.clearTimeSet = setInterval(() => {
        this.socket.send(JSON.stringify(parmas))
      }, 20000)
    },
    // 清除定时器
    clearTimer() {
      clearInterval(this.clearTimeSet)
    },
    // 查看大图
    viewPicture(content) {
      this.handleVisible = true
      this.viewPictureSrc = content
    }
  },
  destroyed() {
    // 销毁监听
    if (this.socket !== '') {
      this.socket.onclose = this.close
      this.socket.close()
      // console.log('退出页面时关闭连接')
      this.clearTimer()
    }
  }
}
</script>
<style lang="less" scoped>
.layoutBox {
  width: 100%;
  height: calc(100vh - 160px);
  display: flex;
  justify-content: space-between;
  // border: 1px solid peru;
  .siderBox {
    width: 260px;
    height: 100%;
    // background: turquoise;
    border: 1px solid #26fbf3;
    text-align: center;
    .ant-menu {
      background: transparent;
      color: #fff;
      border: none;

      .ant-menu-item {
        background: rgba(44, 63, 97, 0.3);
      }
    }
    h3 {
      margin: 25px auto;
    }
  }
  .rightBox {
    width: calc(100% - 290px);
    // width: 260px;
    height: 100%;
    // background: pink;
    // border: 1px solid #26fbf3;
    box-sizing: border-box;
    padding: 10px;
    .headerBox {
      width: 100%;
      height: 50px;
      line-height: 50px;
      text-align: center;

      border: 1px solid #26fbf3;
      // background: coral;
      margin-bottom: 20px;
    }
    .chactBox {
      height: calc(100% - 80px);
      // background: salmon;
      border: 1px solid #26fbf3;
      display: flex;
      flex-direction: column;
      flex: 1;
      .chactDiv {
        height: calc(100% - 280px);
        // background: lightgoldenrodyellow;
        border: 1px solid #26fbf3;
        .ulBox {
          position: relative;
          color: #fff;
          list-style: none;
          line-height: 30px;
          padding: 15px;
          .Local {
            width: 100%;
            text-align: right;
            span {
              border: 1px solid turquoise;
              border-radius: 5px;
              display: inline-block;
              padding: 6px 18px;
            }
          }
          .Misconduct {
            text-align: left;
            width: 100%;
            span {
              border: 1px solid turquoise;
              border-radius: 5px;
              display: inline-block;
              padding: 6px 18px;
            }
          }
        }
      }
      .inputDiv {
        height: 280px;
        // background: rgb(204, 204, 104);
        border: 1px solid #26fbf3;
        position: relative;
        .handleDiv {
          position: absolute;
          bottom: 0px;
          width: 100%;
          // background: lightgreen;
          display: flex;
          justify-content: flex-end;
          .ant-btn {
            margin: 10px;
          }
        }
      }
    }
  }
}
</style>